using OhioState.AssetManaged;
using OhioState.Graphics;

namespace OhioState.Graphics.OpenGL
{
    public abstract class TextureHandler : OpenGLObject, ITexture, IOpenGLResource
    {
        protected ITexture _textureProxy;
        protected TextureGL _realTexture;
        protected TextureHandler(IAssetManaged proxyObject)
            : base(proxyObject)
        {
            if (proxyObject is ITexture)
            {
                _textureProxy = proxyObject as ITexture;
            }
        }
        public int Width
        {
            get { return _realTexture.Width; }
        }
        public int Height
        {
            get { return _realTexture.Height; }
        }
        public int Depth
        {
            get { return _realTexture.Depth; }
        }
        public TexelFormat TexelType
        {
            get { return _realTexture.TexelType; }
        }
        public bool Create
        {
            get { return _created; }
            set { _created = value; }
        }

        public virtual void bind()
        {

            if (!_created)
            {
                this.Invalid = true;
                createGLTexture();
                _created = true;
            }
            _realTexture.bind();
            if (this.Invalid)
            {
                this.Invalid = false;
                updateGLTexture();
            }
        }
       
        public virtual void unbind()
        {
            _realTexture.unbind();
        }

        #region IHardwareResource<uint> Members
        public uint GUID
        {
            get {
                if (!_created)
                {
                    bind();
                    unbind();
                }
                return _realTexture.GUID;
            }
        }
        #endregion

        protected bool _created = false;
        protected abstract void createGLTexture();
        protected abstract void updateGLTexture();
        protected bool formatChanged()
        {
            //
            // Check to see if the basic shape has changed.
            //
            if (_realTexture.Width != _textureProxy.Width || _realTexture.Height != _textureProxy.Height
                || _realTexture.Depth != _textureProxy.Depth || _realTexture.TexelType.Format != _textureProxy.TexelType.Format
                || _realTexture.TexelType.Type != _textureProxy.TexelType.Type)
            {
                return true;
            }
            return false;
        }
    }
}
